package com.cy.bigevent.Controller;

import com.cy.bigevent.Service.UserService;
import com.cy.bigevent.pojo.Result;
import com.cy.bigevent.pojo.User;
import com.cy.bigevent.utils.JwtUtil;
import com.cy.bigevent.utils.Md5Util;
import com.cy.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.apache.ibatis.annotations.Param;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
//    jakarta.validation.ConstraintViolationExce@ption:
//    register.username: 需要匹配正则表达式"^\S{5,16}$"
    @RequestMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
        User byUserName = userService.findByUserName(username);
        if (byUserName == null) {
            userService.register(username, password);
            return Result.success();
        }else{
            return Result.error("用户名已存在");
        }
    }
    @RequestMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password) {
        //根据用户明查询用户
        User loginUser = userService.findByUserName(username);
        //判断用户是否存在
        if (loginUser == null) {
            return Result.error("用户不存在或用户名错误");
        }
        //判断密码是否匹配
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
            //登陆成功
//            return Result.success("jwt token");
        }
        return Result.error("密码错误");
    }
    @GetMapping("/userInfo")
    public Result userInfo(/*@RequestHeader("Authorization") String token8*/) {
        //根据用户名查询用户
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        //优化为threadlocal全局参数传递
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }
    //update
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }
//    更新头像
    //需要对avatarURL进行参数校验
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    //修改密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params) {
        //进行修改密码前要进行判断
        /**
         * 1、三个参数是否都非空（原密码，新密码，重复输入）
         * 2、原密码是否正确
         * 3、两次填写的密码是否一致
         */
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
//        * 1、三个参数是否都非空（原密码，新密码，重复输入）
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }
//        * 2、原密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        if (!userService.findByUserName(username)
                .getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码填写不正确");
        }
//        3、两次填写的密码是否一致
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次密码填写不一致");
        }
        //逻辑判断完成后执行修改密码操作
        userService.updataPwd(newPwd);
        return Result.success();
    }
}
